/*
 * @Author: wuqingchun
 * @Date: 2024-09-20 16:49:30
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-09-20 17:51:12
 */
#include <cstring>

#include <unistd.h>

#include "redis_distributed_lock.h"


int32_t CRedisDistributedLock::Init(const char* pcServerHost, uint16_t usPort)
{
    m_pstRedisCtx = redisConnect(pcServerHost, usPort);
    if (m_pstRedisCtx == nullptr)
    {
        return -1;
    }
    
    return 0;
}

bool CRedisDistributedLock::Accquire()
{
    const char* apcArgs[4];
    
    apcArgs[0] = "SET"; // 命令
    apcArgs[1] = m_strLockKey.c_str();       // key
    apcArgs[2] = "locked";                   // value
    apcArgs[3] = "NX";

    // 使用redis的SET命令实现分布式锁
    //redisReply* pstReply = reinterpret_cast<redisReply *>(redisCommandArgv(m_pstRedisCtx, 3, apcArgs, NULL));

    redisReply* pstReply = (redisReply*)redisCommand(m_pstRedisCtx, "SET dlock locked NX");
    if (pstReply == nullptr)
    {
        // 获取锁失败
        return false;
    }

    if (pstReply->str != nullptr && strcmp(pstReply->str, "OK") == 0)
    {
        // 获取锁成功
        freeReplyObject(pstReply);
        return true;
    }

    if (pstReply->str != nullptr)
    {
        printf("Failed to accquire lock, %s\n", pstReply->str);
    }

    // 获取锁失败
    freeReplyObject(pstReply);
    return false;
}

bool CRedisDistributedLock::Release()
{

}

int main(int argc, char** argv)
{
    CRedisDistributedLock objRedisLock;

    //if (objRedisLock.Init("192.168.56.102", 6379) != 0)
    if (objRedisLock.Init("127.0.0.1", 6379) != 0)
    {
        printf("Init error\n");
        return -1;
    }

    if (objRedisLock.Accquire())
    {
        printf("Accquire sucessfully\n");
    }
    else
    {
        printf("Accquire failure\n");
    }


    pause();

    return 0;
}